package com.example.unveil_the_leader.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.unveil_the_leader.common.Result;
import com.example.unveil_the_leader.common.RegisterMsg;
import com.example.unveil_the_leader.common.ResultCode;
import com.example.unveil_the_leader.entity.Users;
import com.example.unveil_the_leader.service.UsersService;
import com.example.unveil_the_leader.mapper.UsersMapper;
import com.example.unveil_the_leader.utils.GetTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Random;

/**
* @author XCT
* @description 针对表【users】的数据库操作Service实现
* @createDate 2024-01-26 15:58:16
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

    @Autowired
    private UsersMapper usersMapper;

    @Autowired(required = false)
    private JavaMailSender sender; // 引入Spring Mail依赖后，会自动装配到IOC容器。用来发送邮件


    @Override
    public Result login(String username, String password) {
        Users usersByName = usersMapper.selectByUsername(username);
        if(usersByName==null){
            return Result.error(ResultCode.ERROR.code, "用户名输入有误，当前暂无该用户信息");
        }else{
            Users user_login = usersMapper.loginByUsername(username, password);
            if(user_login==null){
                return Result.error("200","账户密码错误");
            }else{
                return Result.success(user_login);
            }
        }
    }

    @Override
    public Result getCode(String mail, HttpServletRequest request) {
        try{
            // 生成 6 位数字验证码
            Random random = new Random();
            String code = random.nextInt(8999) + 1000+"";// 验证码
            // 当前时间
            LocalDateTime currentTime = LocalDateTime.now();

            //2min有效时间
            LocalDateTime expireTime = currentTime.plusMinutes(2);

            //存储到session
            request.getSession().setAttribute("expireTime", expireTime);

            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("【测试验证码】验证消息"); // 发送邮件的标题
            message.setText("登录操作，验证码："+ code + "，切勿将验证码泄露给他人，本条验证码有效期2分钟。"); // 发送邮件的内容
            message.setTo(mail+"@qq.com"); // 指定要接收邮件的用户邮箱账号

            message.setFrom("3158614516@qq.com"); // 发送邮件的邮箱账号，注意一定要和配置文件中的一致！

            sender.send(message); // 调用send方法发送邮件即可
            System.out.println(mail);
            //先用的session可以采用security
            request.getSession().setAttribute("qq",mail);
            request.getSession().setAttribute("code",code);
            request.getSession().setAttribute("expireTime",expireTime);
            request.getSession().setMaxInactiveInterval(60*2);
            return Result.success(code);
        }
        catch (Exception e){
            return Result.error("200","发送失败");
        }

    }

    @Override
    public Result register(String username, String password, String qq, String code,HttpServletRequest request) {
        String QQcode = (String)request.getSession().getAttribute("code");
        RegisterMsg registerMsg = checkCode(qq, code, request);
        Boolean result = registerMsg.getResult();
        if(result){
            Users userByUsername = usersMapper.selectByUsername(username);
            if(userByUsername!=null){
                return Result.error("200","当前用户名已经被使用，请更换");
            }else{
                Users userByQQ = usersMapper.selectByQQ(qq);
                if(userByQQ!=null){
                    return Result.error("200","当前qq号码已被使用");
                }else{
                    Users user=new Users();
                    user.setUserName(username); //设置用户名
                    user.setName(username); //设置真实用名
                    user.setQq(qq); //设置用户qq
                    user.setEmail(qq+"@qq.com");
                    user.setPassword(password); //设置密码
                    user.setCreateTime(GetTimeUtil.getTime()); //设置账号创建时间
                    usersMapper.register(user);
                    return Result.success("注册成功");
                }
            }
        }else{
            return Result.error("200","注册失败");
        }

    }

    @Override
    public Result updateMsg(Users users) {
        usersMapper.userUpdate(users);
        return Result.success("修改成功");
    }



    @Override
    public RegisterMsg checkCode(String vqq,String vcode,HttpServletRequest request) {
        HttpSession session=request.getSession();
        //先用的session可以采用security
        String qq= (String) session.getAttribute("qq");
        String code=   (String)session.getAttribute("code");
        LocalDateTime expireTime = (LocalDateTime) session.getAttribute("expireTime");
        LocalDateTime currentTime = LocalDateTime.now();
        // 检查验证码是否过期
        if (expireTime != null && currentTime.isBefore(expireTime)) {
            // 验证码有效，执行相应逻辑
            // return "验证码过期了！";
            if (vqq.equals(qq) && vcode.equals(code)){
                return new RegisterMsg(true,"验证码通过");
            }
            else {
                return new RegisterMsg(false,"验证码输入错误");
            }
        } else {
            // 验证码已过期，执行相应逻辑
            session.removeAttribute("qq");
            session.removeAttribute("code");
            return new RegisterMsg(false,"验证码过期");
        }
    }
}




